import axios from 'axios'

const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  withCredentials: false
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('Token')
    console.log('请求拦截器中的token:', token)
    if (token) {
      config.headers['Token'] = token
      console.log('设置请求头:', config.headers)
    }
    config.retry = 3
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      const config = error.config
      if (!config || !config.retry) {
        console.log('请求超时，无法重试')
        return Promise.reject(error)
      }
      config.retry -= 1
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(api(config))
        }, 1000)
      })
    }
    
    if (error.response?.status === 401) {
      // token 过期或无效，清除本地存储并跳转到登录页
      console.log('token 过期或无效，清除本地存储并跳转到登录页')
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 登录接口
export const login = (username, password, code, uuid, url = '/login') => {
  return api.post(url, {
    username,
    password,
    code,
    uuid
  })
}

// 退出登录接口
export const logout = async () => {
  try {
    // 先设置退出登录标记
    sessionStorage.setItem('isLogout', 'true')
    console.log('设置退出登录标记')
    
    // 清除localStorage
    localStorage.clear()  // 清除localStorage中的所有数据
    console.log('清除localStorage中的所有数据')
    
    // 清除sessionStorage，但保留isLogout标记
    const isLogout = sessionStorage.getItem('isLogout')
    sessionStorage.clear()
    if (isLogout) {
      sessionStorage.setItem('isLogout', isLogout)
    }
    console.log('清除sessionStorage中的所有数据，保留isLogout标记')
    
    // 等待一下确保存储操作完成
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 最后跳转到登录页
    window.location.href = '/login'
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}

export default api 